package com.yuelan.codelib.utils;

import java.lang.reflect.Field;
import java.util.List;

import android.app.ActivityManager;
import android.content.Context;

public class ProcessUtil
{
	public static String getProcessName(Context context)
	{
		final int PROCESS_STATE_TOP = 2;
		
		ActivityManager.RunningAppProcessInfo currentInfo = null;
		Field field = null;
		try
		{
			field = ActivityManager.RunningAppProcessInfo.class.getDeclaredField("processState");
		}
		catch (Exception ignored)
		{
			
		}
		
		ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		
		List<ActivityManager.RunningAppProcessInfo> appList = am.getRunningAppProcesses();
		for (ActivityManager.RunningAppProcessInfo app : appList)
		{
			if (app.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND
					&& app.importanceReasonCode == ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN)
			{
				Integer state = null;
				try
				{
					state = field.getInt(app);
				}
				catch (Exception e)
				{
					
				}
				
				if (state != null && state == PROCESS_STATE_TOP)
				{
					currentInfo = app;
					break;
				}
			}
		}
		if (currentInfo == null)
		{
			return "";
		}
		return currentInfo.processName;
	}

	/**
	 * 判断进程是否在运行
	 * @param context
	 * @param processName
	 * @return
	 */
	public static boolean processIsRunning(Context context, String processName)
	{
		ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		
		List<ActivityManager.RunningAppProcessInfo> appList = am.getRunningAppProcesses();
		for (ActivityManager.RunningAppProcessInfo app : appList)
		{
			if (app.processName.equals(processName))
				return true;
		}
		return false;
	}

}
